package com.baizhi.controller;

import com.baizhi.entity.Node;
import com.baizhi.service.RoleService;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("permission")
public class PermissinController {

    @Resource
    private RoleService roleService;

    @RequestMapping("getNodes")
    public List<Node> getAllNodes() {
        //List<Node> nodes = new ArrayList<>();

        //查询一级目录，因为一级目录父id是null，传入null 参数
        List<Node> allNodes = roleService.findSubNodes(null);
        List<Node> nodes = fetch(allNodes);
      /*  allNodes.forEach(s -> {
            List<Node> subNodes = roleService.findSubNodes(s.getId());
            Node node = new Node();
            node.setId(s.getId());
            node.setTitle(s.getTitle());
            node.setChildren(fetch(subNodes));
            nodes.add(node);
        });*/
        return nodes;

    }

    public List<Node> fetch(List<Node> subNodes) {
        List<Node> children = new ArrayList();
        if (subNodes.size() == 0) return children;
        subNodes.forEach(s -> {
            Node node = new Node();
            node.setId(s.getId());
            node.setTitle(s.getTitle());
            List<Node> nexNodes = roleService.findSubNodes(s.getId());
            node.setChildren(fetch(nexNodes));
            children.add(node);
        });
        return children;
    }
}
